import requests,re
import execjs
import json
import os
import sys
 
def get_last_5days_data(currentpath:str, code: str):
    '''获取指定股票最近5天的分时线数据(含当天)'''
    url = 'https://finance.sina.com.cn/realstock/company/%s/hisdata/klc_cm.js' % (code) # 指定日期对应的最近5天的分时数据 KLC_ML_szxxxxxx=
    prefix = 'KLC_ML_%s=' % code
    res = requests.get(url)
    if res.status_code == 200:
        reg = re.compile(r'%s"(.+?)"' % prefix)
        data = reg.findall(res.text)
    sdkpath = '%s/sf_sdk.js' % (currentpath)
    with open(sdkpath, 'r') as f:
        js_file = f.read()
    ctx = execjs.compile(js_file)
    days_data = data[0].split(',')
    for i in range(len(days_data)):
        arr = ctx.call('decode', days_data[i])
        print(json.dumps(arr))
        print('#')
 
def get_month_data(currentpath:str, code: str, date: str):
    '''获取日期所在月份的所有分时数据(如果是当前月，不含当天的)'''
    year = date[0:4]
    month = date[5:7]
    url = 'http://finance.sina.com.cn/realstock/company/%s/hisdata/%s/%s.js?d=%s' % (code, year, month, date) # 指定日期所在月份的所有分时数据  MLC_szxxxxxx_2021_04=
    prefix = 'MLC_%s_%s_%s=' % (code, year, month)
    res = requests.get(url)
    if res.status_code == 200:
        reg = re.compile(r'%s"(.+?)"' % prefix)
        data = reg.findall(res.text)
    sdkpath = '%s/sf_sdk.js' % (currentpath)
    with open(sdkpath, 'r') as f:
        js_file = f.read()
    ctx = execjs.compile(js_file)
    days_data = data[0].split(',')
    for i in range(len(days_data)):
        arr = ctx.call('decode', days_data[i])
        arrLen = len(arr)
        currdate = ''
        for j in range(arrLen):
            data = arr[j]
            if data.get('date') is not None:
                currdate = data['date']
            data['date'] = currdate
        if date in currdate:
            print(arr)
 
if __name__=='__main__':
    get_month_data(sys.argv[1], sys.argv[2], sys.argv[3])
    #print(sys.argv[1], sys.argv[2], sys.argv[3])

